import { onUnmounted, ref } from 'vue';

type DebounceFunction<T extends (...args: any[]) => void> = (...args: Parameters<T>) => void;

/**
 * 创建一个防抖钩子函数
 *
 * @param fn 需要防抖的函数
 * @param delay 防抖延迟时间（毫秒）
 * @returns 防抖后的函数
 */
export function useDebounce<T extends (...args: any[]) => void>(fn: T, delay: number): DebounceFunction<T> {
  const timer = ref<NodeJS.Timeout | null>(null);

  const debounce = (...args: Parameters<T>) => {
    if (timer.value) {
      clearTimeout(timer.value);
    }
    timer.value = setTimeout(() => {
      fn(...args);
    }, delay);
  };

  onUnmounted(() => {
    if (timer.value) {
      clearTimeout(timer.value);
    }
  });

  return debounce as DebounceFunction<T>;
}
